<template>
  <view class="affair_record">
    <view class="record_item">
      <view class="header">
        <view class="header_left">
          <view class="num">{{ index + 1 }}</view>
          <view class="label">备注:</view>
        </view>

        <view class="handle">
          <view
            v-if="orderStatus !== 4 && msg.userId == userinfo.user_id"
            class="handle_item"
          >
            <view @click="handleEdit" class="editBtn">
              <image src="/static/images/edit2.png" mode=""></image>
            </view>
            <view @click="handleDel" class="delBtn">
              <image src="/static/images/del.png" mode=""></image>
            </view>
          </view>
        </view>
      </view>

      <view class="content" :style="{ border: isLast ? 'none' : '' }">
        <view class="des">
          <view style="margin-bottom: 20rpx">{{ form.disposeDesc }}</view>
        </view>
        <view class="imgBox">
          <image-drag-sort
            :max="9"
            @changeList="changeImg"
            :list="disposeImgUrl"
            :disabled="true"
          ></image-drag-sort>
          <!-- <image  :src="item.url" mode=""  v-for="(item,index) in form.disposeImgUrl" :key="index"/> -->
        </view>

        <!-- <view class="length" v-if="isEdit">{{
          form.disposeDesc.length + "/300"
        }}</view> -->
        <view class="member">
          <image src="/static/images/maintain/add.png" mode=""></image>
          <text style="color: #333; margin-right: 8rpx">{{
            msg.malfunctionRecordVO[0].userName
          }}</text>
          {{ msg.malfunctionRecordVO[0].recordLog }}
        </view>
        <view class="time" style="margin-bottom: 20rpx;">{{ msg.malfunctionRecordVO[0].updateTime }}</view>
      </view>
    </view>
  </view>
</template>

<script>
import ImageDragSort from '@/components/image-drag-sort/img-and-video.vue';
import { editCHeckRecord } from '@/apis/workOrder.js';
import { update, del, setRecord, fetchDetail } from '@/apis/repair.js';
import { mapState, mapActions } from 'vuex';
import { hanleToken } from '@/utils/utils.js';
export default {
	components: {
		ImageDragSort,
	},
	props: {
		// 对象数组
		msg: {
			type: Object,
		},
		// 索引值
		index: {
			type: Number,
		},
		// 我自己是否还未签退
		isPlanStatus: {
			type: Boolean,
			default: false,
		},
		// 是否最后一个item
		isLast: {
			type: Boolean,
		},
		// 订单状态,如果是4不可以编辑
		orderStatus: {
			type: Number,
		},
		// 是否正在编辑的标识,每次只可以编辑一条数据
		editing: {
			type: Boolean,
			default: false,
		},
		planId: {
			type: [String, Number],
		},
		elevatorId: {
			type: [String, Number],
		},
		// 24小时内是否可以编辑
		// updateStatus: {
		//   type: Boolean,
		// },
	},
	watch: {
		msg() {
			this.initData();
		},
	},
	created() {
		this.initData();
	},
	computed: {
		...mapState('user', ['userinfo']),
		// disabled() {
		//   if (this.status === 4 || !this.isEdit) {
		//     return true;
		//   } else {
		//     return false;
		//   }
		// },
	},
	data() {
		return {
			disposeImgUrl: [],
			isEdit: false, // 是否整条记录在编辑中
			form: {
				checkContentName: '',
			},
			planOrderStatus: '',
			// isEditDes:false// ,描述是否在编辑中
		};
	},
	methods: {
		initData() {
			let msg = JSON.parse(JSON.stringify(this.msg));
			delete msg.malfunctionRecordVO;
			this.form = msg;
			// this.form.checkTypeName = this.form.partNames.split("&amp;&amp;");
			// let arr = [];
			// for (let i = 0; i < this.form.disposeImgUrl.length; i++) {
			//   this.form.disposeImgUrl[i];
			//   arr.push(this.form.disposeImgUrl[i].url);
			// }
			this.disposeImgUrl = this.form.disposeImgUrl;
			console.log(this.disposeImgUrl,'this.disposeImgUrl');
			console.log('this.form ', this.planId, this.form);
		},
		changeImg(list) {
			this.disposeImgUrl = list;
		},
		// 删除记录
		async handleDel() {
			console.log(this.isPlanStatus, this.orderStatus, 'this.isPlanStatus');
			if (this.orderStatus < 4 && !this.isPlanStatus) {
				uni.showToast({
					title: '请先签到后再操作',
					icon: 'none',
				});
				return;
			}
			// await this.getDetail();
			if (this.orderStatus === 4) {
				this.$emit('hadDone');
				return;
			} else {
				uni.showModal({
					title: '',
					content: '确认删除本条任务记录?',
					confirmText: '确定',
					confirmColor: '#0091ff',
					cancelText: '取消',
					cancelColor: '#ccc',
					success: (res) => {
						if (res.confirm) {
							del({ ids: this.msg.id }).then((res) => {
								if (res) {
									uni.showToast({
										title: '删除成功',
										icon: 'none',
									});
									this.$emit('update', { type: 'del' });
								}
							});
						}
					},
				});
			}
		},
		// 添加配件
		// handleAdd(){
		//   let {partNames,partIds,disposeDesc,disposeImgUrl} = this.msg
		//   let obj = {
		//     partsId: partIds,
		//     partsName: partNames,
		//     desc: disposeDesc,
		//     imgUrls: disposeImgUrl,
		//   }
		//   hanleToken('set','partsUpObj',obj)
		//   uni.navigateTo({
		//     url: `/pageModules/parts/applyParts?malPartId=${this.msg.id}&id=${this.elevatorId}&fromPlanId=${this.planId}`,
		//   });
		// },
		// 配件详情
		// toPartsDetail(item){
		//   uni.navigateTo({
		//     url: `/subpages/approve/partApprovalDetail?type=3&id=${item.planId}`,
		//   });
		// },
		// resStr(name){
		//   return name ? name.replaceAll("&amp;&amp;"," > "):''
		// },

		// resNameColor(pStatus){
		//   return this.examineArr.find(item=>item.arrStatus.includes(pStatus)) || {}
		// },

		handleEdit() {
			if (this.orderStatus < 4 && !this.isPlanStatus) {
				uni.showToast({
					title: '请先签到后再操作',
					icon: 'none',
				});
				return;
			}

			// // 如果有正在编辑的数据不可以点击
			// if (this.editing) {
			//   uni.showToast({
			//     title: "尚有未保存的记录",
			//     icon: "none",
			//   });
			// } else {
			//   this.isEdit = !this.isEdit;
			//   this.$emit("changeEditStatus", { isEdit: this.isEdit });
			// }
			// this.$emit("changeEditStatus", { isEdit: this.isEdit });
			this.$emit('editRecord', {msg:this.msg,index:this.index});
		},
		// 更新内容
		async handleUpdate() {
			await this.getDetail();
			if (this.orderStatus == 4 && !this.updateStatus) {
				console.log('完成');

				this.$emit('hadDone');
			} else {
				const { disposeDesc } = this.form;
				if (disposeDesc === '' && this.disposeImgUrl.length === 0) {
					uni.showToast({
						title: '图片为必填项',
						icon: 'none',
					});
				} else {
					console.log('提交新建记录');
					uni.showLoading({
						title: '保存中',
						mask: true,
					});
					let imgs = this.disposeImgUrl;
					let arr = [];
					for (let i = 0; i < imgs.length; i++) {
						arr.push({
							url: imgs[i],
							type: 'image',
						});
					}
					this.form.disposeImgUrl = arr;
					this.form.planId = this.planId;
					const all = [
						this.handleDes(this.form, this.msg),
						update({ ...this.form, userId: this.userinfo.user_id }),
					];
					Promise.all(all).then((res) => {
						console.log(res, 'all的值', 88888);
						if (res) {
							this.isEdit = !this.isEdit;
							setTimeout(() => {
								uni.showToast({
									title: '保存成功',
									icon: 'none',
								});
							}, 200);
							this.$emit('update', { isEdit: this.isEdit, type: 'update' });
						}
					});
				}
			}
		},
		handleDes(res, olddata) {
			return new Promise((resolve) => {
				let result = '';
				let imgUrl = this.disposeImgUrl || [];
				let oimgUrl = [];
				for (let i = 0; i < olddata.disposeImgUrl.length; i++) {
					olddata.disposeImgUrl[i];
					oimgUrl.push(olddata.disposeImgUrl[i].url);
				}
				let recordHistory = res.disposeDesc || '';
				let orecordHistory = olddata.disposeDesc || '';
				if (JSON.stringify(imgUrl) != JSON.stringify(oimgUrl)) {
					if (imgUrl.length == oimgUrl.length) {
						result = result + '更新了照片';
					} else {
						if (imgUrl.length > oimgUrl.length) {
							result =
                result + '上传了' + (imgUrl.length - oimgUrl.length) + '张图片';
						} else {
							result =
                result + '删除了' + (oimgUrl.length - imgUrl.length) + '张图片';
						}
					}
				}
				if (recordHistory != orecordHistory) {
					result = result + (result.length > 0 ? '，' : '');
					result = result + (orecordHistory ? '更新了描述' : '添加了描述');
				}
				if (!result) {
					resolve();
				}

				const params = {
					planId: this.planId,
					userId: this.userinfo.user_id,
					checkHistoryId: this.form.id,
					recordLog: result,
					recordDataValue: this.form,
				};
				console.log('params', params);
				editCHeckRecord(params).then((res) => {
					resolve(res);
				});
			});
		},
		getDetail() {
			return new Promise((resolve) => {
				fetchDetail({ planId: this.planId }).then((res) => {
					if (res) {
						this.planOrderStatus = res.data.status;
						resolve();
					}
				});
			});
		},
	},
};
</script>

<style lang="scss" scoped>
.affair_record {
  .title {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    // padding-bottom: 22rpx;
    padding-left: 20rpx;
  }

  .length {
    text-align: right;
    padding-bottom: 20rpx;
    color: #ccc;
    font-size: 24rpx;
  }

  .record_item {
    // display: flex;
    width: 100%;

    .header {
      display: flex;
      padding-bottom: 8rpx;
      padding-top: 22rpx;
      justify-content: space-between;
      align-items: center;
      .header_left {
        display: flex;
        align-items: center;
      }

      .num {
        width: 40rpx;
        height: 40rpx;
        font-size: 26rpx;
        color: #0091ff;
        background: #ddf0ff;
        border-radius: 0rpx 4rpx 4rpx 0rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 16rpx;
      }
      .label {
        font-size: 24rpx;
        color: #999;
      }

      .name {
        display: flex;
        margin-left: 16rpx;
        // width: 354rpx;
        flex-wrap: wrap;
      }

      .handle {
        // width: 412rpx;
        display: flex;
        height: 100%;

        .handle_item {
          display: flex;
          justify-content: flex-end;
          // width: 100%;
          padding-top: 2rpx;
          box-sizing: border-box;
          width: 280rpx;
        }

        image {
          width: 32rpx;
          height: 32rpx;
          // margin-top: 2rpx;
        }

        .addBtn {
          border-right: 2rpx solid #e9e9e9;
          // justify-content: center;
          padding-right: 12rpx;
          font-size: 12px;
          color: #666666;
          margin: 0 14rpx 0 10rpx;
        }
        .editBtn {
          border-right: 2rpx solid #e9e9e9;
          justify-content: center;
          padding-right: 30rpx;
        }

        .delBtn {
          padding-left: 20rpx;
        }

        view {
          display: flex;
          // flex: 1;
          justify-content: flex-end;
        }

        .saveBtn {
          color: #0091ff;
          width: 100%;
          display: flex;
          align-items: center;
          font-size: 24rpx;

          text {
            margin-left: 4rpx;
          }
        }
      }
    }

    .content {
      // margin-left: 56rpx;
      padding-left: 56rpx;
      padding-bottom: 32rpx;
      // border-bottom: 1;
      border-bottom: 2rpx solid #eeeeee;

      .type {
        font-size: 24rpx;
        color: #666;
        // margin-top: 8rpx;
      }

      .imgBox {
        margin: 20rpx 0;
      }

      .des {
        font-size: 28rpx;
        color: #333;
      }

      .member {
        // margin-top: 20rpx;
        color: #999;
        font-size: 24rpx;
        display: flex;
        align-items: center;
        margin-bottom: 6rpx;

        image {
          width: 24rpx;
          height: 24rpx;
          margin-right: 10rpx;
        }
      }

      .time {
        margin-left: 34rpx;
        color: #999;
        font-size: 24rpx;
      }

      .linkPlan {
        padding: 20rpx 16rpx;
        background: #f6f6f6;
        border-radius: 8rpx;
        margin-bottom: 20rpx;

        // display: flex;
        .plan_L {
          .L_row {
            margin-bottom: 10rpx;
            font-size: 12px;
            font-weight: 400;
            color: #666666;
            display: flex;
            view:nth-of-type(1) {
              width: 180rpx;
            }
            view:nth-of-type(2) {
              color: #333;
              // width: 500rpx;
              flex: 1;
            }
            .row_plan {
              text {
                display: inline-block;
                padding: 2rpx 6rpx;
                border-radius: 8rpx;
              }
              text:nth-of-type(1) {
                margin-right: 16rpx;
              }
            }
          }
          .L_row:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>
